package com.yiibai;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.sql.*;

public class EmployeeTag extends TagSupport {
	private String number;
	
	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://localhost/testdb?useSSL=false&characterEncoding=utf8", "root", "123456");
			PreparedStatement ps = con.prepareStatement("SELECT name,education,age FROM `employees` ORDER BY id DESC limit "+this.number);
			//ps.setInt(1, Integer.parseInt(this.number));
			System.out.println("number => "+this.number);
			ResultSet rs = ps.executeQuery();
			if (rs != null) {
				// column name
				out.write("<table border='1'>");
				out.write("<tr>");
				out.write("<th>姓名</th><th>学历</th><th>年龄</th>");
				out.write("</tr>");
				// column value

				while (rs.next()) {
					out.write("<tr>");
					out.write("<td>" + rs.getString("name") + "</td><td>" + rs.getString("education") + "</td><td>" + rs.getString("age") + "</td>");
					out.write("</tr>");
				}
				out.write("</table>");
			}
			con.close();
		} catch (Exception e) {
			System.out.println(e);
		}
		return SKIP_BODY;
	}
}